﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            #region 例1
            Type type = typeof(Teacher);
            //得到此类型所有方法  
            MethodInfo[] methods = type.GetMethods();
            foreach (MethodInfo method in methods)
            {
                //得到此方法的所有特性  
                object[] attributes = method.GetCustomAttributes(false);
                foreach (object o in attributes)
                {
                    //判断是否是自己定义的特性  
                    if (o.GetType() == typeof(WahAttribute))
                    {
                        //强转取得值  
                        WahAttribute waha = (WahAttribute)o;
                        Console.WriteLine("author=" + waha.Author);
                        Console.WriteLine("description=" + waha.Description);
                    }
                }
            } 
            #endregion
            #region  例2
            ISay g = new GovermentSay();
            Print(g);
            #endregion
            Console.Read();
        }
        public static void Print(ISay say)
        {
            System.Reflection.MemberInfo info = say.GetType();

            BlockAttribute att =
                 (BlockAttribute)Attribute.GetCustomAttribute(info, typeof(BlockAttribute));
            if (att.Level == Level.Yes)//如果标签是Yes
                Console.WriteLine(say.GetType().ToString() + ": " + say.Say());
            else//如果是No
                Console.WriteLine(say.GetType().ToString() + ": " + "I Love the contry!");
        }
    }
    [Block(Level.Yes)]
    public class GovermentSay : ISay
    {
        public string Say()
        {
            return "Our country is the most democratic country";
        }
    }
    [Block(Level.NO)]
    public class PeopleSay : ISay
    {
        public string Say()
        {
            return "We need rights";
        }
    }
    [AttributeUsage(AttributeTargets.Class)]//指定Attribute的使用范围，只能在class级别使用
    public class BlockAttribute : Attribute
    {
        public Level Level
        {
            get;
            set;
        }

        public BlockAttribute(Level level)//在实例化的时候，就指定Block是Yes还是No
        {
            Level = level;
        }
    }
    public enum Level
    {
        NO,
        Yes
    }
}
